package com.zhongxi.guoyuan.view.seller.provinceselector;

import android.content.Intent;
import android.content.SharedPreferences;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.seller.BillProvice;
import com.zhongxi.guoyuan.entity.seller.ShopProviceInfo;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.seller.SellerBeautifulStoreLoginActivity;
import com.zhongxi.guoyuan.view.seller.provinceselector.SideBar.OnTouchingLetterChangedListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class ProvinceMainActivity extends BaseActivity {
    private ListView sortListView;
    private SideBar sideBar;
    private TextView dialog;
    private SortAdapter adapter;
    private ClearEditText mClearEditText;
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<SortModel> SourceDateList;

    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;
    private List<ShopProviceInfo> data = new ArrayList<>();
    private Map<String, String> map;
    public static final int resultCodeValu = 123;

    @Override
    public void initView() {
        setContentView(R.layout.activity_listview_sort_main);
        initTitle();
        tvTitle.setText("店铺列表");
        ShopProviceInfo info = new ShopProviceInfo("", "全部美容院");
        data.add(info);
        // 实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        pinyinComparator = new PinyinComparator();

        sideBar = (SideBar) findViewById(R.id.sidrbar);
        dialog = (TextView) findViewById(R.id.dialog);
        sideBar.setTextView(dialog);
        sortListView = (ListView) findViewById(R.id.country_lvcountry);
    }

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<SortModel> filledData(String[] date) {
        List<SortModel> mSortList = new ArrayList<SortModel>();

        for (int i = 0; i < date.length; i++) {
            SortModel sortModel = new SortModel();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }

    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        List<SortModel> filterDateList = new ArrayList<SortModel>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = SourceDateList;
        } else {
            filterDateList.clear();
            for (SortModel sortModel : SourceDateList) {
                String name = sortModel.getName();
                if (name.indexOf(filterStr.toString()) != -1 || characterParser.getSelling(name).startsWith(filterStr.toString())) {
                    filterDateList.add(sortModel);
                }
            }
        }

        // 根据a-z进行排序
        Collections.sort(filterDateList, pinyinComparator);
        adapter.updateListView(filterDateList);
    }

    @Override
    protected void initData() {
        super.initData();
        getServer(Url.INNER_SHOP_QUERY, null, "", true, null, "get");

        //SourceDateList = filledData(getResources().getStringArray(R.array.date));
        //   String[] item = {"添加", "继承实体", "对象JContacts", "（可直接", "使用JContacts", "实体对象", "，根据自己是", "否需要扩展实体属性）"};
//        SourceDateList = filledData(item);

    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        BillProvice billProvice = gson.fromJson(response, BillProvice.class);
        MyApplication.getInstance().setSpValue(billProvice.getSafeobj());
        if (billProvice.getData() != null && !"".equals(billProvice.getData())) {
            data.addAll(billProvice.getData());
        }
        //  List<String> nameList = new ArrayList<>();
        SourceDateList = new ArrayList<SortModel>();
        map = new HashMap<>();
        for (int i = 0; i < data.size(); i++) {
            //    nameList.add(data.get(i).getName());
            map.put(data.get(i).getName(), data.get(i).getId());
            SortModel sortModel = new SortModel();
            sortModel.setName(data.get(i).getName());
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(data.get(i).getName());
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }
            SourceDateList.add(sortModel);
        }

        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        adapter = new SortAdapter(this, SourceDateList);
        sortListView.setAdapter(adapter);

        mClearEditText = (ClearEditText) findViewById(R.id.filter_edit);

        // 根据输入框输入值的改变来过滤搜索
        mClearEditText.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 当输入框里面的值为空，更新为原来的列表，否则为过滤数据列表
                filterData(s.toString());
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse result = gson.fromJson(response, BaseResponse.class);
        if (null != result.getSafeobj() && !"".equals(result.getSafeobj()))
            MyApplication.getInstance().setSpValue(result.getSafeobj());

        if (result.getCode() == 9002) {
            showShortToast("登录已失效，请重新登录");
            SharedPreferences sharedPrefrences = getSharedPreferences(Url.APP_SP, MODE_PRIVATE);
            sharedPrefrences.edit().putString("beautifulcredentials", "").commit();
            startAct(SellerBeautifulStoreLoginActivity.class);
            finish();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        // 设置右侧触摸监听
        sideBar.setOnTouchingLetterChangedListener(new OnTouchingLetterChangedListener() {

            @Override
            public void onTouchingLetterChanged(String s) {
                // 该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    sortListView.setSelection(position);
                }

            }
        });


        sortListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // 这里要利用adapter.getItem(position)来获取当前position所对应的对象
//                Toast.makeText(getApplication(), ((SortModel) adapter.getItem(position)).getName(), Toast.LENGTH_SHORT).show();
                String name = ((SortModel) adapter.getItem(position)).getName();
                String value = map.get(name);
                Intent intent = new Intent();
                intent.putExtra("value", value);
                intent.putExtra("key", ((SortModel) adapter.getItem(position)).getName());
                setResult(resultCodeValu, intent);
                finish();
            }
        });
    }
}
